require 'Korundum'
include KDE

require 'model'
require 'time_updater'
require 'list_selection_controller'

class MainController
	attr_reader :main_view
	
	def initialize
	end

	def main_view=(view)
		@main_view = view
		connect(view)
	end

	def run
		@main_view.show
		@app.exec
	end
	
	def init
		#FIXME: remove this dependency with korundum
		description = "An application to log your time usage"
		version     = "1.0"
		copyright   = "(C) 2006 Sebastian Galkin"
		aboutData   = AboutData.new("jatit", "Jatit", version, description, AboutData::License_GPL, copyright)
		aboutData.addAuthor("Sebastian Galkin", "Design and programming", "paraseba@gmail.com")

		CmdLineArgs.init(ARGV, aboutData)
		@app = Application.new
	end

	private

	def connect(view)
		view.open_selected.add_observer {ask_workspace_to_open}
		view.start_selected.add_observer {|task_id| start_task(task_id)}
		view.stop_selected.add_observer {|task_id| stop_task(task_id)}
		view.time_up.add_observer {tictac}
	end

	def clear_view
		@main_view.clear_tree
	end

	def ask_workspace_to_open
		cont = ListSelectionController.new
		ws_id = cont.select_workspace
		open_workspace(ws_id) if ws_id 
	end

	def open_workspace(id)
		ws = Workspace.find(id)
		clear_view
		ws.projects.each {|p| add_project(p)}		
	end
	
	def add_project(project)
		@main_view.add_project_data(project.id, project.name, project.description)
		project.tasks.each {|t| add_task(t, project)}
	end

	def add_task(task, project)
		@main_view.add_task_data(task.id, task.name, task.description, project.id)
	end

	def start_task(id)
		task = Task.find(id)
		task.start
		@main_view.mark_started(id)
	end
	
	def stop_task(id)
		task = Task.find(id)
		task.stop(nil) #FIXME
		@main_view.mark_stopped(id)
	end

	def tictac
		update_task_times
	end
		
	def update_task_times
		tasks = Task.running_tasks
		if tasks.size > 0
			time_data = tasks.map {|t| [t.id, t.today, t.total]}
			@main_view.update_times(time_data)
		end
	end
end
